﻿using BlueportCoffee.model;
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace BlueportCoffee.http
{
    /// <summary>
    /// 咖啡机数据调用
    /// </summary>
    public class BaseService
    {
        public static string url_start = "https://api.robotstroll.com/";
        private static BaseService instance;
        private BaseService() { }
        public static BaseService Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new BaseService();
                }
                return instance;
            }
        }
        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
        public string ServerGet(string url)
        {
            string result = string.Empty;
            try
            {
                url = url_start + url;
                HttpWebRequest request = null;
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;

                request.Method = "GET"; //使用get方式发送数据
                request.ContentType = "application/json";
                request.Accept = "application/json";
                request.Referer = null;
                request.AllowAutoRedirect = true;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                using (StreamReader sr = new StreamReader(stream))
                {
                    result = sr.ReadToEnd();
                }
                //Console.Write(result);
                return result;
            }
            catch (Exception)
            {
                return result;
            }
        }
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
        /// <summary>
        /// SHA1 加密 
        /// </summary>
        /// <param name="content">需要加密字符串</param>
        /// <param name="encode">指定加密编码</param>
        /// <param name="upperOrLower">大小写格式（大写：X2;小写:x2）默认小写</param> 
        public static string SHA1Encrypt(string content, Encoding encode, string upperOrLower = "x2")
        {
            try
            {
                var buffer = encode.GetBytes(content);//用指定编码转为bytes数组
                var data = SHA1.Create().ComputeHash(buffer);
                var sb = new StringBuilder();
                foreach (var t in data)
                {
                    sb.Append(t.ToString(upperOrLower));
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                return "SHA1加密出错：" + ex.Message;
            }
        }
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="ismake"></param>
        /// <returns></returns>
        public string HttpPostRaw(string url, string data, bool ismake = false)
        {
            string value = "";
#pragma warning disable CS0168 // 声明了变量，但从未使用过
            try
            {
                url = url_start + url;
                HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(url);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                reqest.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
                reqest.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                long unixTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                reqest.Headers["timestamp"] = unixTimestamp.ToString();
                reqest.Headers["nonce"] = IPorPortInfo.Instance.ProductId + IPorPortInfo.Instance.DeviceName;
                reqest.Headers["signature"] = SHA1Encrypt(unixTimestamp.ToString() + IPorPortInfo.Instance.ProductId + IPorPortInfo.Instance.DeviceName + IPorPortInfo.Instance.token,Encoding.UTF8);
                reqest.Method = "POST";
                reqest.ContentType = "application/json";
                Stream stream = reqest.GetRequestStream();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(data);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
                stream.Close();
                if (ismake)
                    reqest.Timeout = 1000;
                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                HttpWebResponse response = (HttpWebResponse)reqest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                value = sr.ReadToEnd();
                response.Close();
                return value;
            }
            catch (Exception ex)
            {
                // error = ex.ToString();
                return "";
            }
#pragma warning restore CS0168 // 声明了变量，但从未使用过
        }
    }
}
